<template>
	<div class="tinymcebox">
		<Editor v-model="contentValue"
				:init="init" :disabled="disabled"
				id="tinymce" ref="tinymceEditor"
				:placeholder="placeholder" @onClick="onClick"/>
		<!--		:before-close="DialogBeforeClose"
					@mousedown.native="dialogMousedown($event)"
					@mouseup.native="dialogMouseup($event)"-->
		<el-dialog
			title="提示"
			v-model="addVisible"
			append-to-body
			width="500px"
		>
			<el-form ref="form" :model="watermarkForm" label-position="top">
				<el-form-item label="请输入水印文字(空为删除水印)" prop="name">
					<el-input v-model="watermarkForm.name" placeholder="请输入水印文字"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="sureForm">确定</el-button>
				<el-button @click="remove">取消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import API from "@/api";
import Editor from '@tinymce/tinymce-vue'
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/silver'
import 'tinymce/icons/default'
// import config from "@/config"
// import 'tinymce/models/dom'

// 引入编辑器插件
import 'tinymce/plugins/code'  //编辑源码
import 'tinymce/plugins/image'  //插入编辑图片
import 'tinymce/plugins/media'  //插入视频
import 'tinymce/plugins/link'  //超链接
import 'tinymce/plugins/preview'//预览
import 'tinymce/plugins/template'//模板
import 'tinymce/plugins/table'  //表格
import 'tinymce/plugins/pagebreak'  //分页
import 'tinymce/plugins/lists'  //列
import 'tinymce/plugins/advlist'  //列
import 'tinymce/plugins/quickbars'  //快速工具条
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/directionality'
import 'tinymce/plugins/visualblocks'
import 'tinymce/plugins/visualchars'
import 'tinymce/plugins/media'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/template'
import 'tinymce/plugins/codesample'
import 'tinymce/plugins/charmap'
import 'tinymce/plugins/pagebreak'
import 'tinymce/plugins/nonbreaking'
import 'tinymce/plugins/anchor'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/help'
import 'tinymce/plugins/emoticons'
import 'tinymce/plugins/autosave'
import 'tinymce/plugins/autoresize'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/print'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/imagetools'
import 'tinymce/plugins/textpattern'
import "tinymce/plugins/emoticons/js/emojis.js"; //必须引入这个文件才有表情图库
import './signature'
import store from "@/store";
import watermark from "@/views/vab/watermark.vue";
import $ from "jquery"

let isTable = (cursorParentTable, e) => {
	let flag = false
	if (flag) {
		console.log(e)
	}
	if (cursorParentTable) {
		// console.log('Cursor is inside a table.', e);
		store.commit("setIsTable", cursorParentTable)
	} else {
		// console.log('Cursor is outside of a table.');
		store.commit("setIsTable", 1)

	}
}
export default {
	computed: {
		watermark() {
			return watermark
		}
	},
	components: {
		Editor
	},
	props: {
		modelValue: {
			type: String,
			default: ""
		},
		placeholder: {
			type: String,
			default: ""
		},
		height: {
			type: Number,
			default: 500,
		},
		disabled: {
			type: Boolean,
			default: false
		},
		plugins: {
			type: [String, Array],
			default: 'signature print preview searchreplace autoresize autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave autoresize'
		},
		toolbar: {
			type: [String, Array],
			default: 'code undo redo restoredraft autoresize | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | blockquote subscript superscript removeformat | bullist numlist | styleselect formatselect fontselect fontsizeselect | table image media charmap emoticons hr pagebreak insertdatetime print preview watermark | fullscreen  | lineheight | signature signature-left signature-right signature-top signature-bottom '
		},
		templates: {
			type: Array,
			default: () => []
		},
		options: {
			type: Object,
			default: () => {
			}
		}
	},
	data() {
		return {
			addVisible: false,
			watermarkForm: {
				name
			},
			init: {
				language_url: 'tinymce/langs/zh_CN.js',
				language: 'zh_CN',
				skin_url: 'tinymce/skins/ui/oxide',
				content_css: "tinymce/skins/content/default/content.css",
				fontsize_formats: "10px 12px 14px 16px 18px 20px 22px 24px 26px 28px 30px",
				emoticons_database_url: '/tinymce/plugins/emoticons/js/emojis.js',
				// menubar: false,
				// statusbar: true,
				plugins: this.plugins,
				toolbar: this.toolbar,
				toolbar_mode: 'sliding',
				height: this.height,
				placeholder: this.placeholder,
				min_height: 750,
				branding: false,
				// auto_focus: true,
				resize: 'both',
				// elementpath: true,
				draggable_modal: true,
				end_container_on_empty_block: true,
				// content_style: "",
				// templates: this.templates,
				// quickbars_selection_toolbar: 'forecolor backcolor bold italic underline strikethrough link',
				// quickbars_image_toolbar: 'alignleft aligncenter alignright',
				// quickbars_insert_toolbar: false,
				image_caption: true,
				image_advtab: true,
				convert_urls: false,
				images_upload_handler: function (blobInfo, succFun, failFun) {
					const data = new FormData();
					data.append("file", blobInfo.blob(), blobInfo.filename());
					API.common.upload.post(data).then((res) => {
						// console.log(res)
						succFun(res.data.uri)
					}).catch(() => {
						failFun("Image upload failed")
					})
				},
				watermark_click: (editor) => {
					// console.log('editor', editor)
					// this.addVisible = true
					this.getWatermark(editor)
				},
				setup: function (editor) {
					editor.on('input blur undo redo execCommand', () => {
						let ifram = document.querySelector(".tinymcebox").querySelector("iframe");
						let height = $(".tinymcebox").find("iframe").contents().find('body').height()
						if (height <= 600) {
							ifram.style.height = 600 + 'px';
						} else {
							ifram.style.height = height + 'px';
						}
					})
					editor.on('init', function () {
						this.getBody().style.fontSize = '14px';
						editor.execCommand('ToggleToolbarDrawer');
					});
					editor.on('OpenWindow', function (e) {
						//FIX 编辑器在el-drawer中，编辑器的弹框无法获得焦点
						var D = document.querySelector('.el-drawer.open')
						var E = e.target.editorContainer
						if (D && D.contains(E)) {
							var nowDA = document.activeElement
							setTimeout(() => {
								document.activeElement.blur()
								nowDA.focus()
							}, 0)
						}
					})
					editor.on('NodeChange', function (e) {
						var cursorParentTable = editor.dom.getParent(editor.selection.getNode(), 'table');
						isTable(cursorParentTable, e)
						// if (cursorParentTable) {
						//   self.$emit('getTable',e);
						//   console.log('Cursor is inside a table.',e);
						// } else {
						//   self.$emit('getTable','no');
						//   console.log('Cursor is outside of a table.');
						// }
					});
					editor.ui.registry.addButton('watermark', {
						icon: 'color-levels',
						tooltip: '水印插入',
						onAction: () => {
							editor.getParam('watermark_click')(editor)
						}
					})
				},
				...this.options
			},
			contentValue: this.modelValue,
			editor: null
		}
	},
	watch: {
		modelValue(val) {
			this.contentValue = val
		},
		contentValue(val) {
			this.$emit('update:modelValue', val);
		}
	},
	mounted() {
		tinymce.init({})
	},
	methods: {
		EditorOnsize() {
			setTimeout(() => {
        let ifram = document.querySelector(".tinymcebox").querySelector("iframe");
        let height = $(".tinymcebox").find("iframe").contents().find('body').height()
        if (height <= 600) {
          ifram.style.height = 600 + 'px';
        } else {
          ifram.style.height = height + 'px';
        }
      },500)
		},
		/**水印*/
		getWatermark(editor) {
			this.editor = editor
			this.addVisible = true
		},
		/**水印确定按钮点击*/
		sureForm() {
			var tinymcebox = $(".tinymcebox").find("iframe").contents();
			tinymcebox.find('.mask_div').remove()
			var defaultSettings = {
				watermark_txt: this.watermarkForm.name,
				watermark_x: 20, //水印起始位置x轴坐标
				watermark_y: 20, //水印起始位置Y轴坐标
				watermark_rows: 8, //水印行数
				watermark_cols: 20, //水印列数
				watermark_x_space: 80, //水印x轴间隔
				watermark_y_space: 50, //水印y轴间隔
				watermark_color: '#aaa', //水印字体颜色
				watermark_alpha: 0.3, //水印透明度
				watermark_fontsize: '15px', //水印字体大小
				watermark_font: '微软雅黑', //水印字体
				watermark_width: 180, //水印宽度
				watermark_height: 80, //水印长度
				watermark_angle: 20 //水印倾斜度数
			};
			if (arguments.length === 1 && typeof arguments[0] === "object") {
				var src = arguments[0] || {};
				for (var key in src) {
					if (src[key] && defaultSettings[key] && src[key] === defaultSettings[key]) continue;
					else if (src[key]) defaultSettings[key] = src[key];
				}
			}
			var oTemp = '';
			//获取页面最大宽度
			var page_width = Math.max(tinymcebox.find('body').width());
			var cutWidth = page_width * 0.0150;
			page_width = page_width - cutWidth;
			//获取页面最大高度
			// console.log(tinymcebox.find('body').height())
			var page_height = Math.max(tinymcebox.find('body').height());
			//如果将水印列数设置为0，或水印列数设置过大，超过页面最大宽度，则重新计算水印列数和水印x轴间隔
			if (defaultSettings.watermark_cols == 0 || (parseInt(defaultSettings.watermark_x + defaultSettings.watermark_width * defaultSettings.watermark_cols + defaultSettings.watermark_x_space * (defaultSettings.watermark_cols - 1)) > page_width)) {
				defaultSettings.watermark_cols = parseInt((page_width - defaultSettings.watermark_x + defaultSettings.watermark_x_space) / (defaultSettings.watermark_width + defaultSettings.watermark_x_space));
				defaultSettings.watermark_x_space = parseInt((page_width - defaultSettings.watermark_x - defaultSettings.watermark_width * defaultSettings.watermark_cols) / (defaultSettings.watermark_cols - 1));
			}
			//如果将水印行数设置为0，或水印行数设置过大，超过页面最大长度，则重新计算水印行数和水印y轴间隔
			if (defaultSettings.watermark_rows == 0 || (parseInt(defaultSettings.watermark_y + defaultSettings.watermark_height * defaultSettings.watermark_rows + defaultSettings.watermark_y_space * (defaultSettings.watermark_rows - 1)) < page_height)) {
				defaultSettings.watermark_rows = parseInt((defaultSettings.watermark_y_space + page_height - defaultSettings.watermark_y) / (defaultSettings.watermark_height + defaultSettings.watermark_y_space));
				defaultSettings.watermark_y_space = parseInt(((page_height - defaultSettings.watermark_y) - defaultSettings.watermark_height * defaultSettings.watermark_rows) / (defaultSettings.watermark_rows - 1));
			}
			var x;
			var y;
			for (var i = 0; i < defaultSettings.watermark_rows; i++) {
				y = defaultSettings.watermark_y + (defaultSettings.watermark_y_space + defaultSettings.watermark_height) * i;
				for (var j = 0; j < defaultSettings.watermark_cols; j++) {
					x = defaultSettings.watermark_x + (defaultSettings.watermark_width + defaultSettings.watermark_x_space) * j;
					var mask_div = document.createElement('div');
					mask_div.id = 'mask_div' + i + j;
					mask_div.className = 'mask_div';
					mask_div.appendChild(document.createTextNode(defaultSettings.watermark_txt));
					//设置水印div倾斜显示
					mask_div.style.webkitTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
					mask_div.style.MozTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
					mask_div.style.msTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
					mask_div.style.OTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
					mask_div.style.transform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
					mask_div.style.visibility = "";
					mask_div.style.position = "absolute";
					mask_div.style.left = x + 'px';
					mask_div.style.top = y + 'px';
					mask_div.style.overflow = "hidden";
					mask_div.style.zIndex = "9999";
					//让水印不遮挡页面的点击事件
					mask_div.style.pointerEvents = 'none';
					mask_div.style.opacity = defaultSettings.watermark_alpha;
					mask_div.style.fontSize = defaultSettings.watermark_fontsize;
					mask_div.style.fontFamily = defaultSettings.watermark_font;
					mask_div.style.color = defaultSettings.watermark_color;
					mask_div.style.textAlign = "center";
					mask_div.style.width = defaultSettings.watermark_width + 'px';
					mask_div.style.height = defaultSettings.watermark_height + 'px';
					mask_div.style.display = "block";
					oTemp += $(mask_div).clone().wrap('<div></div>').parent().html();
				}
			}
			tinymcebox.find('body').append(oTemp)
			tinymcebox.find('body').click()
			this.$emit('changeHtml', this.editor.getContent())
			this.remove()
		},
		remove() {
			this.$refs.form.resetFields()
			this.addVisible = false
		},
		onClick(e) {
			this.$emit('onClick', e, tinymce)
		},
	}
}
</script>
<style>
#tinymce {
	overflow: scroll;
}
</style>
<style lang="scss">
.print_box {
	.el-tabs__header {
		margin-bottom: 0;
	}
}

.tppText {
	font-size: 22px;
}

.tinymcebox {
	height: 100%;
	overflow: auto;
}

.tinymcebox .tox, .tox-tinymce {
	height: 100%;
}

.tinymcebox .tox .tox-edit-area__iframe {
	width: 800px;
	height: 550px;
	min-height: 30px;
	padding: 50px 2px;
	background: #fff;
	margin: 30px auto;
	flex: none;
	position: static;
}

.tinymcebox .tox .tox-edit-area {
	background: #ededed;
	min-height: 600px;
	overflow-y: auto;
}
</style>
